import React, { Component } from 'react';
import { Card, Button, Table, Modal, message } from 'antd';
import LinkButton from '../../components/link-button';
import SaveForm from './save-form';
import { ExclamationCircleOutlined } from '@ant-design/icons';
import { v4 as uuidv4 } from 'uuid';

let sourceUsersData = [{
    "_id": {
      "$oid": "5fd06735fa244c0b10cadec7"
    },
    "username": "Tom",
    "password": "202cb962ac59075b964b07152d234b70",
    "phone": "123242434",
    "email": "sd",
    "role_id": "5e188bb874c89321209fedda",
    "create_time": 1555061512734,
    "__v": 0
  },{
    "_id": {
      "$oid": "5fd0675bfa244c0b10cadec8"
    },
    "username": "Cindy",
    "password": "202cb962ac59075b964b07152d234b70",
    "phone": "12324233434",
    "email": "plp",
    "role_id": "5e0d7292bd72914ee8e714d4",
    "create_time": 1555062212734,
    "__v": 0
  },{
    "_id": {
      "$oid": "5fd06791fa244c0b10cadec9"
    },
    "username": "Jim",
    "password": "202cb962ac59075b964b07152d234b70",
    "phone": "72612189",
    "email": "feedback@outlook.com",
    "role_id": "5e0d7292bd72914ee8e714d4",
    "create_time": 1552062212734,
    "__v": 0
  },{
    "_id": {
      "$oid": "5fd067affa244c0b10cadeca"
    },
    "username": "Kira",
    "password": "202cb962ac59075b964b07152d234b70",
    "phone": "224249",
    "email": "wait@outlook.com",
    "role_id": "5fcdca798e518d46807aa484",
    "create_time": 1252062212734,
    "__v": 0
  },{
    "_id": {
      "$oid": "5fd06aaf97daee1b6c09b1cd"
    },
    "username": "admin",
    "password": "21232f297a57a5a743894a0e4a801fc3",
    "phone": "224249",
    "email": "admin@outlook.com",
    "role_id": "5e175a134bce5e36d48fb4db",
    "create_time": 1212062212734,
    "__v": 0
  },{
    "_id": {
      "$oid": "5fd09192efe9692bd0dd40de"
    },
    "username": "test2",
    "password": "202cb962ac59075b964b07152d234b70",
    "phone": "123",
    "email": "123",
    "role_id": "5e188bb874c89321209fedda",
    "create_time": 1607504274441,
    "__v": 0
  }].map(v => {
      return {
          ...v,
          ['_id']: v['_id']['$oid']
      }
  });

let sourceRolesData = [{
    "_id": {
      "$oid": "5e0d7292bd72914ee8e714d4"
    },
    "name": "测试",
    "auth_time": 1607481252131,
    "auth_name": "admin",
    "create_time": 1554639521749,
    "menus": [
      "/category",
      "/home"
    ]
  },{
    "_id": {
      "$oid": "5e171d55d59eb648d4ed66a8"
    },
    "menus": [
      "/home",
      "/products",
      "/category",
      "/product",
      "/charts/pie"
    ],
    "name": "测试",
    "create_time": 1578573141547,
    "auth_name": "admin",
    "auth_time": 1607406938634
  },{
    "_id": {
      "$oid": "5e175a134bce5e36d48fb4db"
    },
    "menus": [
      "all",
      "/home",
      "/products",
      "/category",
      "/product",
      "/user",
      "/role",
      "/charts",
      "/charts/bar",
      "/charts/line",
      "/charts/pie"
    ],
    "name": "管理员",
    "create_time": 1578588691768,
    "auth_name": "admin",
    "auth_time": 1578588698490
  },{
    "_id": {
      "$oid": "5e188bb874c89321209fedda"
    },
    "menus": [
      "/home",
      "/charts/bar",
      "/charts",
      "/charts/line",
      "/charts/pie",
      "/role"
    ],
    "name": "员工",
    "create_time": 1578666936202,
    "auth_name": "admin",
    "auth_time": 1607330722391
  },{
    "_id": {
      "$oid": "5fcdca798e518d46807aa484"
    },
    "menus": [
      "/category"
    ],
    "name": "你好",
    "create_time": 1607322233401,
    "auth_time": 1607411041057,
    "auth_name": "admin"
  },{
    "_id": {
      "$oid": "5fcdcb428e518d46807aa485"
    },
    "menus": [],
    "name": "哈哈哈",
    "create_time": 1607322434116
  },{
    "_id": {
      "$oid": "5fcdcb528e518d46807aa486"
    },
    "menus": [],
    "name": "哈哈啊",
    "create_time": 1607322450051
  },{
    "_id": {
      "$oid": "5fcdcd638e518d46807aa488"
    },
    "menus": [],
    "name": "123",
    "create_time": 1607322979807
  }].map(v => {
      return {
        ...v,
        ['_id']: v['_id']['$oid']
      }
  });


/**
 * 用户
 */
class User extends Component {

    state = {
        loading: false,
        users: [],
        roles: [],
        modalTitle: '',
        visible: false,
        user:{}
    };
    

    /**
     * 初始化列
     */
     initColumns = () => {
        this.columns = [
            {
              title: '用户名',
              dataIndex: 'username',
            },
            {
                title: '邮箱',
                dataIndex: 'email',
            },
            {
                title: '电话',
                dataIndex: 'phone',
            },  
            {
                title: '注册时间',
                dataIndex: 'create_time',
            },
            {
                title: '所属角色',
                dataIndex: 'role_id',
                render: (role_id) => this.roleNames[role_id]
            },
            {
                title: '操作',
                width: 300,
                // 返回需要显示的界面
                render: (row) => (
                    <span>
                        <LinkButton onClick={() => this.handleUpdate(row) } >修改</LinkButton>
                        <LinkButton onClick={() => this.handleDel(row)}>删除</LinkButton>
                    </span>
                ),
            }
        ];
    }

    
    /**
     * 获取用户列表数据
     */
    getUser = () => {
        this.setState({loading: true});
        setTimeout(() => {
            this.initRoleNames(sourceRolesData);
            this.setState({ 
                users: [...sourceUsersData], 
                roles: [...sourceRolesData],
                loading: false 
            });
        }, 1000);
    }

    
    /**
     * 初始化获取所有角色名称
     * 此方法有点秀
     */
    initRoleNames(roles){
        const roleNames = roles.reduce((pre, role) => {
            pre[role['_id']] = role.name;
            return pre;
        },{});

        console.log('initRoleNames:', roleNames);

        this.roleNames = roleNames;
    }

    
    /**
     * 保存
     */
    handleOk = () => {
        this.form.current.validateFields().then(values => {
            const user = this.form.current.getFieldsValue();

            // 更新
            if(this.state.user['_id']){
                sourceUsersData.forEach(v => {
                    if(v['_id'] === this.state.user['_id']){
                        v.username = user.username;
                        v.phone = user.phone;
                        v.email = user.email;
                        v.role_id = user.role_id
                    }
                });
            }else{
                sourceUsersData.unshift({
                    '_id': uuidv4(),
                    'create_time': new Date().getTime(),
                    ...user
                });
            }

            this.setState({
                visible: false
            },() => {
                this.form.current.resetFields();
            });

            this.getUser();
        });
    }

    /**
     * 打开修改
     */
    handleUpdate = (row) => {
        this.setState({
            modalTitle: '修改用户',
            user: row,
            visible: true
        });
    }

    
    /**
     * 删除
     */
    handleDel = (row) => {
        Modal.confirm({
            title: '确定删除吗？',
            icon: <ExclamationCircleOutlined />,
            onOk: () => {
                setTimeout(() => {
                    sourceUsersData = sourceUsersData.filter(v => v['_id'] !== row['_id']);
                    this.getUser();
                    message.success('删除成功');
                }, 1000);
            }
        });
    }


    UNSAFE_componentWillMount(){
        this.initColumns();
    }

    
    componentDidMount(){
        this.getUser();
    }



    render() { 
        const { loading, users, modalTitle, visible, user, roles } = this.state;

        const title = <Button type="primary" onClick={() => this.setState({ modalTitle: '创建用户',visible: true})}>创建用户</Button>

        return (
            <Card title={title}>
                <Table 
                loading={loading}
                bordered
                rowKey="_id"
                columns={this.columns} 
                dataSource={users} 
                pagination={{ defaultPageSize: 5, showQuickJumper: true, }}
                />

                <Modal 
                title={modalTitle} 
                visible={visible} 
                onOk={this.handleOk} 
                onCancel={() => this.setState({visible: false})}
                >
                <SaveForm 
                setForm={(form) => {this.form = form}}
                user={user}
                roles={roles}
                />
                </Modal>
            </Card>
        );
    }
}
 
export default User;